package com.wlcb.jpower.chat.task.action;

import com.wlcb.jpower.chat.service.customer.ChatService;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.im.cache.SessionCache;
import com.wlcb.jpower.utils.RedisHelpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @description: 定时处理未完成用户
 * @author: liwenfei
 */
@Component
public class ClearSessionTask {
    @Autowired
    private AccessTask accessTask;
    @Autowired
    private OffTask offTask;
    @Autowired
    private ChatService chatService;


    @Scheduled(cron = "0 0/10 * * * ?")
    public void clear() {
        RedisHelpUtils.RedisLock redisLock = RedisHelpUtils.getRedisLock();
        String lockKey = "clear";
        boolean is = redisLock.tryLock(lockKey);
        if (is) {
            try {
                offTask.off();
                List<DataPacket.Wait> waitUsers = chatService.getWaitUsers();
                SessionCache.writeAll(DataPacket.wait(waitUsers, ChatConfigConstant.UserType.CUSTOMER));
            } finally {
                redisLock.runlock(lockKey);
            }
        }


    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void access() {
        RedisHelpUtils.RedisLock redisLock = RedisHelpUtils.getRedisLock();
        String lockKey = "access";
        boolean is = redisLock.tryLock(lockKey);
        if (is) {
            try {
                accessTask.access();
                List<DataPacket.Wait> waitUsers = chatService.getWaitUsers();
                SessionCache.writeAll(DataPacket.wait(waitUsers, ChatConfigConstant.UserType.CUSTOMER));
            } finally {
                redisLock.runlock(lockKey);
            }
        }
    }
}
